package project.ccso.top.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import project.ccso.top.dao.MemberDao;
import project.ccso.top.entity.CommodityInfo;
import project.ccso.top.entity.Member;
import project.ccso.top.entity.Province;
import project.ccso.top.util.DBUtil;

/**
 * 会员Dao的实现类
 * @author aibinxiao
 * @date 2018年8月23日 上午10:37:42
 */
public class MemberDaoImpl implements MemberDao {
	private static Logger logger = LoggerFactory.getLogger(MemberDaoImpl.class);
	private DBUtil dbUtil = new DBUtil();

	/**
	 * 根据用户手机号查询用户是否注册
	 */
	@Override
	public boolean queryByPhoneNumber(String telphone) {
		boolean flag = false;
		String sql = "select * from t_member where mem_phone = ?";
		ResultSet rs = dbUtil.executeQuery(sql, new Object[] {telphone});
		try {
			if(rs.next()) {
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
		}
		return flag;
	}

	/**
	 * 用户注册，添加新用户
	 */
	@Override
	public boolean addMember(Member member) {
		boolean flag = false;
		int count = -1;
		String sql = "insert into t_member (mem_phone, mem_password, mem_nickname, mem_portrait, mem_sex, mem_province, mem_city, mem_school, mem_shield_status, mem_reg_time, mem_update_time)";
		count = dbUtil.executeUpdate(sql, member.toObjects());
		if(count == 1) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 用户登录，根据用户输入的手机号和密码，检查数据库中是否有与之相匹配的记录
	 */
	@Override
	public Member login(String account, String password) {
		String sql = "select * from t_member where ";
		ResultSet rs = null;
		if (StringUtils.isNumeric(account)) {
			// 输入的全是数字，则为手机号登陆
			logger.info("用户使用手机号[" + account + "]登录了！");
			sql += "mem_phone = ? and mem_password = ? and mem_shield_status = ?";
			rs = dbUtil.executeQuery(sql, new Object[] {account, password, 0});getClass();
		} else {
				// 输入的全不是数字，则为用户名登陆
			logger.info("用户使用手机号[" + account + "]登录了！");
			sql = "mem_nickname = ? and mem_password = ? and mem_shield_status = ?";
			rs = dbUtil.executeQuery(sql, new Object[] {account, password, 0});
		}
		Member member = null;
		try {
			if(rs.next()) {
				member = new Member(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getInt(6), 
						rs.getString(7), rs.getString(8), rs.getString(9), rs.getInt(10), rs.getString(11), rs.getString(12));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return member;
	}

	/**
	 * 根据用户ID查询用户信息
	 * @param parseInt
	 * @return
	 */
	@Override
	public Member findById(int userId) {
		String sql = "select * from t_member where mem_Id = ?";
		ResultSet rs = dbUtil.executeQuery(sql, new Object[] {userId});
		List<Member> list = new ArrayList<>();
		try {
			while (rs.next()) {
				Member member = new Member(rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getInt(6),rs.getString(7),rs.getString(8),rs.getString(9));
				list.add(member);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			list = null;
		}
		return list.get(0);
	}
	
	/**
	 * 根据用户Id更新用户信息是否成功
	 */
	@Override
	public Boolean upadteMessageById(Member user2) {
		boolean flag = false;
		String sql = "update t_member set mem_phone=?,mem_nickName=?,mem_sex=?,mem_portrait=?,mem_province=?,mem_city=?,mem_school=? where mem_id=?";
		int Result =  dbUtil.executeUpdate(sql, new Object[] {user2.getPhoneNumber(),user2.getNickName(),user2.getSex(),user2.getPortrait(),user2.getProvince(),user2.getCity(),user2.getSchool(),user2.getId()});
		if(Result != -1) {
			return true;
		}
		return false;
	}

	/**
	 * 根据用户Id更新用户密码是否成功
	 */
	@Override
	public Boolean upadtePasswordById(Member user2) {
	
		String sql = "update t_member set mem_password=?where mem_id =? ";
		int Result =  dbUtil.executeUpdate(sql, new Object[] {user2.getPassword(),user2.getId()});
		if(Result != -1) {
			return true;
		}
		return false;
	}

	/**
	 * 查询符合条件的总记录数
	 */
	@Override
	public int countByParams(String id, String nickName, String startDate, String endDate) {
		List<Object> objects = new ArrayList<>();
		int count = 0;
		String sql = "select count(*) from t_member where 1=1";
		if (!StringUtils.isEmpty(id)) {
			sql += " and mem_id = ?";
			objects.add(id);
		}
		if (!StringUtils.isEmpty(nickName)) {
			sql += " and mem_nickname like ?";
			objects.add("%" + nickName + "%");
		}
		if (!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
			startDate += " 00:00:00";
			endDate += " 23:59:59";
			sql += " and mem_reg_time between ? and ?";
		}
		ResultSet rs = dbUtil.executeQuery(sql, objects);
		try {
			while (rs.next()) {
				count = rs.getInt(1);
			}
			logger.info("找到(" + count + ")个符合查询条件的用户信息");
			return count;
		} catch (SQLException e) {
			logger.info("没有找到符合查询条件求的用户信息");
			e.printStackTrace();
			return count;
		}
	}

	/**
	 * 分页查询所有符合条件的用户信息
	 */
	@Override
	public List<Member> findPageByParams(String id, String nickName, String startDate, String endDate, int startIndex,
			int records) {
		List<Member> result = new ArrayList<>();
		List<Object> objects = new ArrayList<>();
		String sql = "select * from t_member where 1=1 ";

		if (!StringUtils.isEmpty(id)) {
			sql += " and mem_id = ?";
			objects.add(id);
		}
		if (!StringUtils.isEmpty(nickName)) {
			sql += " and mem_nickname like ?";
			objects.add("%" + nickName + "%");
		}
		if (!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)) {
			startDate += " 00:00:00";
			endDate += " 23:59:59";
			sql += " and mem_reg_time between ? and ?";
		}
		sql += " limit ? , ?";
		objects.add(startIndex);
		objects.add(records);
		ResultSet rs = dbUtil.executeQuery(sql, objects);
		try {
			while (rs.next()) {
				Member member = new Member(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getInt(6), 
						rs.getString(7), rs.getString(8), rs.getString(9), rs.getInt(10), rs.getString(11), rs.getString(12));
				result.add(member);
			}
		} catch (SQLException e) {
			result = null;
		}
		return result;
	}

	/**
	 * 屏蔽或启用用户
	 */
	@Override
	public boolean updateShieldStatus(int id, int transStatus) {
		boolean flag = false;
		int count = 0;
		String sql = "update t_member set mem_shield_status = ? where mem_id = ?";
		count = dbUtil.executeUpdate(sql, new Object[] {transStatus, id});
		if(count != -1) {
			flag = true;
			if(transStatus == 1) {
				logger.info("id为" + id + "的用户启用成功！");
			}else if(transStatus == 0) {
				logger.info("id为" + id + "的用户启用成功！");
			}
		}
		return flag;
	}
	

	/**
	 * 2.验证手机号是否已经注册Dao实现类
	 *//*
	@Override
	public boolean findByPhoneNumber(String phoneNumber) {
		boolean flag = false;
		String hql = "from Member where phoneNumber = ?";
		List<Member> list = this.getHibernateTemplate().find(hql, phoneNumber);
		if (list != null && list.size() > 0) {
			flag = true;
			logger.info("手机号" + phoneNumber + "已经注册过了！");
		}
		return flag;
	}

	*//**
	 * 3.用户注册Dao实现类
	 *//*
	@Override
	public boolean addMember(Member member) {
		boolean flag = true;
		try {
			this.getHibernateTemplate().save(member);
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	*//**
	 * 4.计算多少符合条件记录条数Dao实现类
	 *//*
	@Override
	public int countByParams(String id, String nickName, String startDate, String endDate) {
		int count = 0;
		// 使用离线条件查询.
		DetachedCriteria criteria = DetachedCriteria.forClass(Member.class);
		if(!StringUtils.isEmpty(id)){
			Integer memId = Integer.valueOf(id);
			criteria.add(Restrictions.idEq(memId));
		}
		if(!StringUtils.isEmpty(nickName)){
			criteria.add(Restrictions.like("nickName", nickName, MatchMode.ANYWHERE));
		}
		if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
			startDate += " 00:00:00";
			endDate += " 23:59:59";
			criteria.add(Restrictions.between("regTime", startDate, endDate));
		}
		// 倒序排序输出:
		criteria.addOrder(Order.asc("id"));
		// 执行查询:
		List<Member> list = this.getHibernateTemplate().findByCriteria(criteria);
		if (list != null && list.size() > 0) {
			count = list.size();
			logger.info("找到("+ list.size() +")个符合查询条件的用户");
		} else{
			logger.info("没有找到符合查询条件求的用户");
		}
		return count;
	}

	*//**
	 * 5.查询出指定开始索引和条数的记录集合Dao实现类
	 *//*
	@Override
	public List<Member> findPageByParams(String id, String nickName, String startDate, String endDate, int startIndex,
			int records) {
		List<Member> result = null;
		// 使用离线条件查询.
		DetachedCriteria criteria = DetachedCriteria.forClass(Member.class);
		if(!StringUtils.isEmpty(id)){
			Integer memId = Integer.valueOf(id);
			criteria.add(Restrictions.idEq(memId));
		}
		if(!StringUtils.isEmpty(nickName)){
			criteria.add(Restrictions.like("nickName", nickName, MatchMode.ANYWHERE));
		}
		if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
			startDate += " 00:00:00";
			endDate += " 23:59:59";
			criteria.add(Restrictions.between("regTime", startDate, endDate));
		}
		// 升序排序输出:
		criteria.addOrder(Order.asc("id"));
		// 执行查询:
		List<Member> list = this.getHibernateTemplate().findByCriteria(criteria, startIndex, records);
		if (list != null && list.size() > 0) {
			result = list;
			logger.info("找到("+ list.size() +")个符合查询条件的用户");
		} else{
			logger.info("没有找到符合查询条件求的用户");
		}
		return result;
	}
	
	*//**
	 * 6.根据ID更新用户状态Dao实现类
	 *//*
	@Override
	public void updateStatus(Integer memId, Integer status) throws Exception {
		String hql = "from Member where id = ?";
		List<Member> list = this.getHibernateTemplate().find(hql, memId);
		if(list!=null && list.size()>0){
			Member member = list.get(0);
			member.setShieldStatus(status);
			this.getHibernateTemplate().saveOrUpdate(member);
		}
	}

	@Override
	public Member getMemberById(String id) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,Integer.parseInt(id));
		if(members.size()>0){
			member=members.get(0);
		}
		return member;
	}

	@Override
	public boolean checkPassword(Member mem) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,mem.getId());
		if(members.size()>0){
			member=members.get(0);
		}
		if(member.getPassword().equals(mem.getPassword())){
			return true;
		}else{
			return false;
		}	
	}

	@Override
	public boolean alterPws(String memId, String newPws) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,Integer.parseInt(memId));
		if(members.size()>0){
			member=members.get(0);
			member.setPassword(newPws);
			this.getHibernateTemplate().saveOrUpdate(member);
			return true;
		}
		return false;
	}

	@Override
	public boolean uploadPic(int memId, String path) {
		String hql="from Member where id=?";
		members=this.getHibernateTemplate().find(hql,memId);
		if(members.size()>0){
			member=members.get(0);
			member.setPortrait(path);
			this.getHibernateTemplate().saveOrUpdate(member);
			return true;
		}
		return false;
	}

	@Override
	public List<Favorite> getCollections(int memId,int offset, int size) {
		String hql="from Favorite where accountId=? order by id desc";
		List<Favorite> favorites=this.getHibernateTemplate().execute(new PageHibernateCallback<Favorite>(hql, new Object[]{memId}, offset, size));
		return favorites;
	}

	@Override
	public int getCollectionsNum(int memId) {
		int count = 0;
		String hql = "select count(*) from Favorite where accountId=?";
		List<Long> list = this.getHibernateTemplate().find(hql,memId);
		if (list != null && list.size() > 0) {
			count = list.get(0).intValue();
			logger.info("收藏商品数："+count);
		}
		return count;
	}

	@Override
	public boolean deleteCollect(int fId) {
		String hql="from Favorite where id=?";
		List<Favorite> favorites=this.getHibernateTemplate().find(hql, fId);
		if(favorites.size()>0){
			favo=favorites.get(0);
			this.getHibernateTemplate().delete(favo);
			return true;
		}
			
		return false;
	}*/
}
